const express = require("express");
const router = express.Router();
const {asyncHandler} = require("../middleWare/getSentResult");
const { getMeun,getAvater } = require("../server/homeInfoServer")
const blogType =require("../server/blogTypeServer");
const {mathCaptcha} = require('../server/captcha');
const {setR,getR,delR,caseTime,addOne} = require('../server/redisServe');
const BnnerServer = require('../server/bannerServer');
const {getBanner,postNum} =require("../routerConfig")

router.get("/meun",asyncHandler(async (req,res,next)=>{
    
    return await getMeun(req.originalUrl);
    
} ))

router.get("/avater",asyncHandler(async(req,res,next)=>{
    return await getAvater(req.originalUrl);
}))
router.get("/blogType",asyncHandler(async (req,res,next)=>{

    res.header("Cache-Control",`max-age=0`);
    const result = await blogType.getBlogType();
    
    return result;
}));

router.get('/captcha',async(req,res,next)=>{
    
    const cap = mathCaptcha();
    const id = req.query.id;
    await setR(5,id,cap.text,{EX:60});
 
    res.type("svg");
    res.header("Cache-Control",`max-age=0`);
    res.status(200).send(cap.data);
  

})

router.post('/captcha',asyncHandler(async(req,res,next)=>{
    const ip  = req.ip + req.originalUrl;

    const Cip = await getR(5,ip);
    console.log(Cip);
    if(!Cip){
       await setR(5,ip,"1",{
            EX: caseTime * 2
        });
    }else if(Cip > postNum) {
        return "请勿频繁提交";
    }
    

    const {id,text} = req.body;
    if(!(id && text)) return "id 或 验证码为空" 
     
    const val = await getR(5,id);
    if(val == text){
        await addOne(ip);
        return true;
    }else{
        return false;
    }


}))

router.get("/getbanner",asyncHandler(async (req,res,next)=>{
  
    const Cr =await getR(0,getBanner);
    if(Cr) return JSON.parse(Cr);
    const result = await BnnerServer.getBanner();
  
    await setR(0,getBanner,JSON.stringify(result),{
        EX:caseTime
    });

    return result;
}))

router.post('/addbanner',asyncHandler(async(req,res,next)=>{
    const { name,thumb,imgUrl} = req.body;
    if(!( thumb && imgUrl)){
        return '缺失必要条件';
    }
    
    const result = await BnnerServer.addBanner(thumb,imgUrl,name);
    await delR(0,getBanner);
    return result




}))

module.exports = router;